<template>
  <ele-modal
    width="740px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    :title="isUpdate ? '修改卡券' : '修改卡券'"
    @update:visible="updateVisible"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="卡券名称:" prop="name">
        <el-input clearable v-model="form.name" placeholder="请输入卡券名称" />
      </el-form-item>

      <el-form-item label="图片:" prop="coupon_img">
        <span slot="label">
          图片

          <el-tooltip placement="top">
            <div slot="content"> 建议上传 200 * 200 尺寸,或者等比例图片 </div>
            <i class="el-icon-question" />
          </el-tooltip>
        </span>
        <!--<ele-image-upload v-model="img" :limit="1" :drag="true" :multiple="false"  @upload="onUpload" /> -->
        <div class="ele-image-upload-list">
          <div
            class="ele-image-upload-item ele-image-upload-button"
            @click="modalPicTap('dan', 'coupon_img', '图片')"
          >
            <div>
              <div tabindex="0" class="el-upload el-upload--text">
                <div class="el-upload-dragger">
                  <i class="el-icon-plus ele-image-upload-icon"></i>
                </div>
                <div
                  class="ele-image-upload-item"
                  style="margin: 0 0 0 0"
                  v-if="form.coupon_img != ''"
                >
                  <div class="el-image">
                    <img
                      :src="form.coupon_img"
                      width="100%"
                      height="100%"
                      class="el-image__inner"
                      style="object-fit: cover"
                    />
                  </div>
                  <div
                    class="ele-image-upload-close"
                    @click="handleRemove('coupon_img')"
                    ><i class="el-icon-close"></i
                  ></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="价格:" prop="price">
        <el-input clearable v-model="form.price" placeholder="价格" />
      </el-form-item>
      <el-form-item label="描述:" prop="desc" v-if="visible ">
        <tinymce-editor v-model="form.desc" :init="editorConfig" />
      </el-form-item>

      <el-form-item label="优惠券:" prop="consumeids">
        <coupon-select v-model="form.consumeids" />
      </el-form-item>

      <el-form-item label="活动开始时间:" prop="start_time">
        <el-date-picker
          v-model="form.start_time"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="活动结束时间:" prop="end_time">
        <el-date-picker
          v-model="form.end_time"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消 </el-button>
      <el-button type="primary" :loading="loading" @click="save"
        >保存
      </el-button>
    </template>
    <uploadPictures
      :isChoice="isChoice"
      :visible.sync="modalPic"
      @getPic="getPic"
      :gridBtn="gridBtn"
      :gridPic="gridPic"
      :title="modalTitle"
    ></uploadPictures>
  </ele-modal>
</template>

<script>
import { add, update } from '@/api/coupon';
import CouponSelect from './coupon-select';
import EleImageUpload from 'ele-admin/es/ele-image-upload';
import uploadPictures from '@/components/uploadPictures';
import TinymceEditor from '@/components/TinymceEditor';

const DEFAULT_FORM = {
  id: 0,
  name: '',
  start_time: '',
  end_time: '',
  desc: '',
  consumeids: [],
  price: '',
  coupon_img: []
};

export default {
  name: 'UserEdit',
  components: { CouponSelect, TinymceEditor, EleImageUpload, uploadPictures },
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  data() {
    return {
      // 表单数据
      form: { ...DEFAULT_FORM },
      // 表单验证规则
      rules: {},
      validMsg: '',
      editorConfig: {
        height: 525,
        relative_urls: false,
        convert_urls: false,
        images_upload_handler: (blobInfo, success, error) => {
          const file = blobInfo.blob();
          // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
          const formData = new FormData();
          formData.append('file', file, file.name);
          request({
            url: '/common/uploadFile',
            method: 'post',
            data: formData,
            onUploadProgress: (e) => {
              // 文件上传进度回调
            }
          })
            .then((res) => {
              if (res.data.code === 0) {
                success(res.data.data.url);
              } else {
                error(res.data.message);
              }
            })
            .catch((e) => {
              error('exception');
            });
        }
      },

      modalTitle: '选择图片',
      modalPic: false,
      isChoice: '单选',
      start_time: '',
      end_time: '',
      // 表单数据
      num: 1,
      value1: [],
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8
      },
      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false
    };
  },
  beforeCreate() {},
  methods: {
    /* 保存编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.loading = true;
        const data = {
          ...this.form,
          consumes: this.form.consumeids.map((d) => {
            return { consumeId: d };
          })
        };
        const saveOrUpdate = this.isUpdate ? update : add;
        saveOrUpdate(data)
          .then((msg) => {
            this.loading = false;
            this.$message.success(msg);
            this.updateVisible(false);
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$messarmge.error(e.message);
          });
      });
    },
    modalPicTap(tit, picTit, openTitle) {
      this.modalTitle = openTitle;
      this.isChoice = tit === 'dan' ? '单选' : '多选';
      this.picTit = picTit;
      this.modalPic = true;
    },
    // 选中图片
    getPic(pc) {
      switch (this.picTit) {
        case 'coupon_img':
          this.form.coupon_img = pc.satt_dir;
          break;
      }
      this.modalPic = false;
    },
    //删除图片
    handleRemove(field) {
      this.form[field] = '';
    },

    /* 更新visible */
    updateVisible(value) {
      this.$emit('update:visible', value);
    }
  },
  watch: {
    visible(visible) {
      if (visible) {
      
        if (this.data) {
          this.$util.assignObject(this.form, {
            ...this.data
          });
            
          this.isUpdate = true;
        } else {
          this.isUpdate = false;
        }

      } else {
        this.$refs['form'].clearValidate();
        this.form = { ...DEFAULT_FORM };
      }
    }
  }
};
</script>
